package com.rambo.dsd.base.servlet;

import com.rambo.tools.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * Create by Rambo on 2017/6/21
 * dao层/web service 层代码生成
 * <p>
 * 访问方式：
 * http://localhost:4048/dao-service-impl/genCode?path=xxxx&po=xxx
 * path 指向到模块即可: D:\Workspaces\MyToys\dao-service-demo\dao-service-api\src\main\java\com\rambo\dsd\sys
 * po 参数为 hibernate 生成的 po 类名
 **/
@WebServlet("/genCode")
public class GenCodeServlet extends HttpServlet {
    private final static Logger log = LoggerFactory.getLogger(GenCodeServlet.class);
    private String module;
    private String dBTableNamePO;
    private String dBTableName;
    private String lowercaseDBTableNamePO;

    public void init() {

    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        String path = request.getParameter("path");
        String po = request.getParameter("po");
        log.info("path:{},po:{}", path, po);
        log.info("1:{}",request.getContextPath());

        if (StringUtil.isEmpty(path) || StringUtil.isEmpty(po)) {
            out.println("必传参数为空！");
            return;
        }

        int tail = StringUtil.lastIndexOf(path, "\\");
        String moduleName = StringUtil.substring(path, tail + 1);
        if (StringUtil.isEmpty(moduleName)) {
            out.println("生成代码路径不符合项目路径规范！");
            return;
        }

        String dBTableName = StringUtil.substring(po, 0, po.indexOf("PO"));
        if (StringUtil.isEmpty(dBTableName)) {
            out.println("PO不符合项目PO规范！");
            return;
        }
        String LowercaseDBTableNamePO = StringUtil.firstLetterLowercase(po);
        log.info("moduleName:{},dBTableName:{},LowercaseDBTableNamePO:{}", moduleName, dBTableName, LowercaseDBTableNamePO);

        this.module = moduleName;
        this.dBTableNamePO = po;
        this.dBTableName = dBTableName;
        this.lowercaseDBTableNamePO = LowercaseDBTableNamePO;

        String daoTemplate = readTemplate("dao.txt");
        outputCode(path.replace("api", "impl") + "\\dao\\inter\\" + this.dBTableName + "Dao.java", replaceKeyWord(daoTemplate));

        String daoimplTemplate = readTemplate("daoimpl.txt");
        outputCode(path.replace("api", "impl") + "\\dao\\impl\\" + this.dBTableName + "DaoImpl.java", replaceKeyWord(daoimplTemplate));

        String wsTemplate = readTemplate("ws.txt");
        outputCode(path + "\\ws\\inter\\" + this.dBTableName + "Ws.java", replaceKeyWord(wsTemplate));

        String wsimplTemplate = readTemplate("wsimpl.txt");
        outputCode(path.replace("api", "impl") + "\\ws\\impl\\" + this.dBTableName + "WsImpl.java", replaceKeyWord(wsimplTemplate));
        out.println("代码生成成功！生成路径:" + path);
    }

    /**
     * 读取模板内容
     *
     * @param templateName 模板名称
     */
    private String readTemplate(String templateName) throws IOException {
        String path1 = Thread.currentThread().getContextClassLoader().getResource("template/" + templateName).getPath();
        FileInputStream fileInputStream = new FileInputStream(path1);
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");

        StringBuilder daoTemplate = new StringBuilder();
        int tempchar;
        while ((tempchar = inputStreamReader.read()) != -1) {
            if (((char) tempchar) != '\r') {
                daoTemplate.append((char) tempchar);
            }
        }
        fileInputStream.close();
        inputStreamReader.close();
        return daoTemplate.toString();
    }

    /**
     * 替换其中的公共字段
     *
     * @param templateContent 要替换的文本
     */
    private String replaceKeyWord(String templateContent) {
        String replace = StringUtil.replace(templateContent, "${module}", this.module);
        String replace1 = StringUtil.replace(replace, "${DBTableNamePO}", this.dBTableNamePO);
        String replace2 = StringUtil.replace(replace1, "${DBTableName}", this.dBTableName);
        return StringUtil.replace(replace2, "${LowercaseDBTableNamePO}", this.lowercaseDBTableNamePO);
    }

    /**
     * 输出代码到指定目录
     *
     * @param outpath       要输出的目录
     * @param outputContext 输出内容
     */
    private void outputCode(String outpath, String outputContext) {
        File file = new File(outpath);

        try (FileOutputStream fop = new FileOutputStream(file)) {
            boolean b = !file.exists() ? file.createNewFile() : file.delete();

            byte[] contentInBytes = outputContext.getBytes();
            fop.write(contentInBytes);
            fop.flush();
            fop.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void destroy() {

    }
}